﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Builder;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Trace.Infrastructure.Repository;

namespace Trace.Infrastructure.Extensions
{
    public static class ServiceCollectionExtension
    {
        public static IServiceCollection AddDbContextService<TDbContext>(this IServiceCollection services, string? connectionString, bool enableSqlLog) where TDbContext : DbContext
        {
            return services.AddDbContext<TDbContext>(builder =>
            {
                builder.UseSqlServer(connectionString, action =>
                {
                    action.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(60), errorNumbersToAdd: null);
                }).EnableSensitiveDataLogging();
                if (enableSqlLog)
                {
                    builder.UseLoggerFactory(LoggerFactory.Create(ConfigureHostBuilder =>
                    {
                        ConfigureHostBuilder.AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information).AddConsole();
                    }));
                }
            });
        }

        public static IServiceCollection AddService(this IServiceCollection services)
        {
            services.AddScoped(typeof(IRepository<>), typeof(BaseRepository<>));
            return services;
        }

        public static void AddJWT(this IServiceCollection services, WebApplicationBuilder builder)
        {
            //builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            //{
            //    //取出私钥
            //    var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]);
            //    options.TokenValidationParameters = new TokenValidationParameters()
            //    {
            //        //验证发布者
            //        ValidateIssuer = true,
            //        ValidIssuer = builder.Configuration["Authentication:Issuer"],
            //        //验证接收者
            //        ValidateAudience = true,
            //        ValidAudience = builder.Configuration["Authentication:Audience"],
            //        //私钥是否过期
            //        ValidateLifetime = true,
            //        //验证私钥
            //        IssuerSigningKey = new SymmetricSecurityKey(secretByte)
            //    };
            //});
        }
    }
}
